#!/usr/bin/python
# -*- coding:utf-8 -*-
# PWM刷新为50Hz，一个周期为20ms情况下,电调的PWM:高电平脉宽为1ms表示停转,高电平脉宽为2ms表示满油门运转
# 舵机PWM:高电平脉宽1.5ms是归中,1ms和2ms分别为左右方向满舵(全转)
import os
import sys
import time
import socket
#import ADS1256
import RPi.GPIO as GPIO
pindc = 12
pinsp = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(pindc, GPIO.OUT)
GPIO.setup(pinsp, GPIO.OUT)
os.system("clear")
dcp = GPIO.PWM(pindc, 50)
spp = GPIO.PWM(pinsp, 50)
dcp.start(0)
spp.start(0)
BUFSIZE = 1024
ip_port = ('0.0.0.0', 9999)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP协议
server.bind(ip_port)
try:
    #ADC = ADS1256.ADS1256()
    # ADC.ADS1256_init()
    while(1):
        #ADC_Value = ADC.ADS1256_GetAll()
        # 200*11.6 7-49  400*22.3 14-99
        # 100*5.6 4-18
        data, client_addr = server.recvfrom(BUFSIZE)
        server.sendto(data.upper(), client_addr)
        print('服务端收到数据', data)
        dc = int(data[:2])
        sp = int(data[2:])
        # dc=int((ADC_Value[3]*5.0/0x7fffff)*22.3)
        if (sp < 58) and (sp > 50):
            sp = 55
        elif (sp >= 98):
            sp = 98
        elif (sp <= 16):
            sp = 16
        if (dc < 58) and (dc > 52):
            dc = 55
        elif (dc >= 98):
            dc = 98
        elif (dc <= 14):
            dc = 14
        print('服务器执行数据', dc, sp)
        dcp.ChangeDutyCycle(dc)
        spp.ChangeDutyCycle(sp)
        print("\33[10A")
# 0x7fffff为16进制代码,对应数值是-8388609
except:
    server.close()
    dcp.stop()
    spp.stop()
    GPIO.cleanup()
    print("\r\nProgram end     ")
    exit()
